const redisClient = require('../../libs/Redis/redisClient').client;
const _ = require('underscore');
const checkThreshold = require('./checkThreshold').checkThreshold;
const mergeData = require('./mergeData').mergeData;
const moment = require('moment');

async function pushRealTimeData(meter) {
    try {
        let deviceNo = meter.deviceNo;
        let data = JSON.parse(meter.data);
        let meterAddr = data.meterAddr;
        data['currentTime'] = moment().format('YYYY-MM-DD HH:mm:ss');
        let currentDate = moment(data['currentTime']).format('YYYY-MM-DD');
        let meterKeyId = `river-course-d-${deviceNo}-${meterAddr}-${currentDate}`;
        if (meter.tn === '1' && meter.fn === '2' && meter.cn === '1' && meter.sn === '28') data = await mergeData(data, meter.matchDevice);
        if (meter.thresholdObj) checkThreshold(deviceNo, data, meter.thresholdObj);
        let meterData = _.omit(data, 'meterAddr');
        let dataObjStr = JSON.stringify(meterData);
        redisClient.rpush(meterKeyId, dataObjStr, redisClient.print);
    } catch (e) {
        console.log(e);
    }
}

exports.pushRealTimeData = pushRealTimeData;